package com.shangxia.monomer.study.thread.lock;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ProjectName: monomer
 * @ClassName: LockDemo
 * @Time: 2021/9/30
 * @Author: zhouy
 * @Description:
 * @Experience:
 */

@Slf4j
public class LockDemo {

    public static void main(String[] args) {
        Resource resource = new Resource();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                resource.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                resource.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                resource.printC();
            }
        }, "C").start();

    }

}

class Resource {
    private Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();
    private Integer num = 0;

    public void printA() {
        lock.lock();
        try {
            while (num % 3 != 0) {
                conditionA.await();
            }
            num++;
            System.out.println("A");
            conditionB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (num % 3 != 1) {
                conditionB.await();
            }
            num++;
            System.out.println("B");
            conditionC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (num % 3 != 2) {
                conditionC.await();
            }
            num++;
            System.out.println("C");
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}